/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javamail.web;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javamail.conn.tcpSockReadWrite;
import javamail.web.util.eContentTypes;

/**
 *
 * @author sriram
 */
public class webServerThread extends Thread {
    tcpSockReadWrite sock = null;
    //public static final String webServerDir = "/home/sriram/";
    //public static final String webServerDir = "/var/www/";
    public static final String webServerDir = "./";
    private boolean debugEnabled = false;
    
    public webServerThread(tcpSockReadWrite socket) {
        sock = socket;
    }
    
    @Override
    public void run() {
        // Handles all the stuff necessary to parse HTTP requests
        // and generating HTTP responses. It also calls necessary
        // APIs to Server Side Scripting software to parse FORM
        // data and performs 
        doWork();
    }
    
    public void doWork() {
        String request = null;
        httpParser parse = new httpParser();

        // Parse the incoming request header line by line
        // parseLine function of the parser returns false
        // when request line and header options are parsed
        // Hence we the loop breaks at the end of header
        do{
            request = sock.readLine();
            if(request != null) {
                if(debugEnabled)
                    System.out.println(request);
            }
        } while (parse.parseLine(request));
        
        // If there are any POST/GET parameters, they will 
        // not be retrieved by readLine as they do not end 
        // with \n. The parameters are not part of header,
        // they are in the body and hence we use readChars
        // to retreive them
        request = sock.readChars();
        if(request != null) {
            parse.parseLine(request);
            if(debugEnabled)
                System.out.println(request);
        }
        
        // Send the appropriate HTTP response using 
        // the parsed data
        sendResponse(parse);
        
        sock.closeAllSockets();
    }
    
    public void sendResponse(httpParser p) {
        String fileName = p.getFileName();
        // Format the file name to point to the web server root directory
        fileName = formatFileName(fileName);
        if(isServerSideScript(fileName)) {
            runServerScript(fileName, p.getParms());
        } else {
            // Send the contents of the requested file to the client
            sendFileContents(fileName);
        }
    }
    
    public String formatFileName(String fileName) {
        // If file starts with a / remove it
        if (fileName.startsWith("/") == true )
            fileName = fileName.substring(1);
        if (fileName.equals(""))
            fileName = "index.html";
        if(!fileName.endsWith(".sss"))
            fileName = webServerDir + fileName;
        return fileName;
    }
    
    
    public void sendFileContents(String fileName){
        // Initialize the HTTP Header generator
        httpGenerator gen = new httpGenerator();
        int count = 0;
        try {
            // Open input stream for the file
            FileInputStream inFile = new FileInputStream(fileName);
            // Generate the HTTP Header
            // Not necessary to add 200 OK. It is the default anyways
            // gen.add200OK();
            gen.addServer();
            gen.addContentType(fileName);
            sock.writeLine(gen.getResponseHeader());
            if(debugEnabled)
                System.out.println(gen.getResponseHeader());
            // Send the requested file back to the client
            // Read 16KB at once and send it to client simultaneously
            byte[] buffer = new byte[16384];
            while ((count = inFile.read(buffer)) > 0)
                sock.write(buffer, 0, count);
            inFile.close();
        }
        catch (FileNotFoundException e) {
            // Generate HTTP 404 Not found if the 
            // requested file is not found in the server
            gen.add404NotFound();
            gen.addContentType(eContentTypes.HTML.toExt());
            sock.writeLine(gen.getResponseHeader());
            if(debugEnabled)
                System.out.println(gen.getResponseHeader());
            
            // Send HTML content as well for user
            sock.writeLine(httpGenerator.getNotFoundResponse());
        } catch (IOException e) {
            sock.writeLine(e.getMessage());
        }
    }
    public boolean isServerSideScript(String fileName) {
        return fileName.endsWith(".sss");
    }
    
    public void runServerScript(String fileName, String parms) {
        httpGenerator gen = new httpGenerator();
        // Generate the HTTP Header
        gen.addServer();
        gen.addContentType(fileName);

        if(isServerSideScript(fileName)) {
            sssParser s = new sssParser(parms);
            // Go ahead with parsing only if there were any 
            // additional parameters sent in the request
            
            if(parms != null && !parms.equals("")) {
                s.parse();
            }

            // The following code is only for mail.sss or status.sss
            // In a normal scenario probably this will need
            // to be seperate server like PHP, ASP for parsing
            if(fileName.toLowerCase().trim().equals("query.sss") ||
               fileName.toLowerCase().trim().equals("action.sss")) {
                // Send the HTTP header to the client
                sock.writeLine(gen.getResponseHeader());
                if(debugEnabled)
                    System.out.println(gen.getResponseHeader());
                String response = new String(s.processInput(fileName));
                sock.writeLine(response);
            } else {
                // Generate HTTP 404 Not found if the 
                // requested file is not found in the server
                gen.add404NotFound();
                gen.addContentType(eContentTypes.HTML.toExt());
                sock.writeLine(gen.getResponseHeader());
                if(debugEnabled)
                    System.out.println(gen.getResponseHeader());
                String response = new String(httpGenerator.inputInvalidResponse("Script file not found!"));
                sock.writeLine(response);
            }
        }
    }

}
